package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"html/template"
	"my_chat/controller"
	"my_chat/logger"
	"my_chat/middlewares"
	"net/http"

	_ "my_chat/docs" // 千万不要忘了导入把你上一步生成的docs

	gs "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
)

//注册模板
func RegisterView(r *gin.Engine) {
	//一次解析出全部模板
	tpl, err := template.ParseGlob("view/**/*")
	if nil != err {
		fmt.Println("验证模版错误")
	}
	//通过for循环做好映射
	for _, v := range tpl.Templates() {
		//
		tplname := v.Name()
		fmt.Println("HandleFunc     " + v.Name())
		r.GET(tplname, func(c *gin.Context) {
			fmt.Println("parse     " + v.Name() + "==" + tplname)
			c.HTML(http.StatusOK, tplname, gin.H{})
		})

	}

}

func SetupRouter(mode string) *gin.Engine {
	if mode == gin.ReleaseMode {
		gin.SetMode(gin.ReleaseMode) // gin设置成发布模式
	}
	r := gin.New()
	r.Use(logger.GinLogger(), logger.GinRecovery(true)) //使用自定义日志中间件
	// 加载模版
	r.LoadHTMLGlob("view/**/*")

	// swagger 在线文档
	r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))

	RegisterView(r)

	// 首页跳转
	r.GET("/", controller.Redirect)

	// 注册逻辑
	r.POST("/user/register", controller.Register)

	// 登入
	r.POST("/user/login", controller.Login)

	// 加载好友
	r.POST("/contact/loadfriend", middlewares.JWTAuthMiddleware(), controller.LoadFriends)

	// 添加好友
	r.POST("/contact/addfriend", middlewares.JWTAuthMiddleware(), controller.AddFriends)

	// 加载群聊
	r.POST("/contact/loadcommunity", middlewares.JWTAuthMiddleware(), controller.LoadCommunity)

	// 加入群聊
	r.POST("/contact/joincommunity", middlewares.JWTAuthMiddleware(), controller.JoinCommunity)

	// 创建群聊
	r.POST("/contact/createcommunity", middlewares.JWTAuthMiddleware(), controller.CreateCommunity)

	//连接聊天web
	r.GET("/chat", middlewares.JWTAuthMiddleware(), controller.Chat)

	// 上传文件到阿里云oss，动静分离，增加性能
	r.POST("/attach/upload", controller.LoadFileOss)

	// 查找用户信息
	r.POST("/user/find", middlewares.JWTAuthMiddleware(), controller.FindUserById)

	// 查找消息
	r.POST("/chat/msg", middlewares.JWTAuthMiddleware(), controller.GetMessages)

	//配置404
	r.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusNotFound, gin.H{
			"msg": "404",
		})
	})
	return r
}
